package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberRespVo;
import org.springframework.web.servlet.HandlerInterceptor;
import com.atguigu.gulimall.cart.vo.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法前。判断用户的登陆信息，并封装传递给controller的目标请求
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo)session.getAttribute(CartConstant.LOGIN_USER);

        if(member != null){
//            用户登录了
            userInfoTo.setUserId(member.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length > 0){
            for (Cookie cookie : cookies) {
                String name =cookie.getName();
                if(name.equals(CartConstant.TEMP_USER_COOKIE_KRY)){
                    userInfoTo.setUserKey(cookie.getValue());
                }
            }
        }
        if(userInfoTo.getUserId() == null && userInfoTo.getUserKey() == null){
//            即没有登陆也没有临时用户
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);

        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Cookie cookie = new Cookie(CartConstant.LOGIN_USER,threadLocal.get().getUserKey());
        cookie.setDomain("gulimall.com");
        cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_EXPIRE);
        response.addCookie(cookie);
        threadLocal.remove();
    }
}
